<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <style></style>
    <div>
      <div class="otp-field">
        <h2>输入验证码</h2>
        <input type="text" maxlength="1" />
        <input type="text" maxlength="1" />
        <input type="text" maxlength="1" />
        <input type="text" maxlength="1" />
      </div>
    </div>
    <script>
      const inputs = document.querySelectorAll(".otp-field input");
      inputs.forEach((input, index) => {
        input.addEventListener("input", () => {
          const value = this.value;
          if (value.length === 1) {
            const nextIndex = index + 1;
            if (nextIndex < inputs.length) {
              const nextInput = inputs[nextIndex];
              nextInput.focus();
            }
          }
        });

        input.addEventListener("keydown", (e) => {
          if (e.key === "Backspace") {
            const value = this.value;
            if (value.length === 0) {
              const prevIndex = index - 1;
              if (prevIndex >= 0) {
                const prevInput = inputs[prevIndex];
                prevInput.focus();
              }
            }
          }
        });
      });
    </script>
  </body>
</html>
